package com.api.utils;

import com.api.common.ResCodeMessageCache;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by PC on 2017/7/4.
 */
public class JsonReturnUtils {


    public static Map<String, Object> fail(String errorCode) {
        return toResultJSON(errorCode, null, null);
    }

    public static Map<String, Object> fail(String errorCode, String errorMsg) {
        return toResultJSON(errorCode, errorMsg, null);
    }

    public static Map<String, Object> fail(String errorCode, Object object) {
        return toResultJSON(errorCode, null, object);
    }

    public static Map<String, Object> fail(String errorCode, String errorMsg, Object object) {
        return toResultJSON(errorCode, errorMsg, object);
    }

    public static Map<String, Object> success(Object object) {
        return toResultJSON("0000", ResCodeMessageCache.getMessageDesc("0000"), object);
    }

    public static Map<String, Object> success() {
        return toResultJSON("0000", ResCodeMessageCache.getMessageDesc("0000"), null);
    }

    public static Map<String, Object> success(Object object, int page, int pageTotal, int total) {
        return toResultJSONForPage("0000", ResCodeMessageCache.getMessageDesc("0000"), object, page, pageTotal, total, null);
    }

    public static Map<String, Object> success(Object object, int page, int pageTotal, int total, Object banner) {
        return toResultJSONForPage("0000", ResCodeMessageCache.getMessageDesc("0000"), object, page, pageTotal, total, banner);
    }

    public static Map<String, Object> toResultJSON(String code, String errorMsg, Object object) {
        Map<String, Object> resultJson = new HashMap<String, Object>();
        if (object != null) {
            boolean isList = object instanceof List;
            String key = isList ? "resultList" : "model";
            resultJson.put(key, object);
        }
        resultJson.put("resCode", code);
        //如果errorMsg存在,则使用,否则就从resCode里查找
        if (StringUtils.isBlank(errorMsg)) {
            errorMsg = ResCodeMessageCache.getMessageDesc(code);
        }
        resultJson.put("resDesc", errorMsg);
        return resultJson;
    }

    public static Map<String, Object> toResultJSONForPage(String code, String errorMsg, Object object, int page, int pageTotal, int total, Object banner) {
        Map<String, Object> resultJson = new HashMap<String, Object>();
        resultJson.put("resultList", object);
        resultJson.put("resCode", code);
        resultJson.put("page", page);
        resultJson.put("pageTotal", pageTotal);
        resultJson.put("total", total);
        if (banner != null) {
            resultJson.put("bannerList", banner);
        }
        //如果errorMsg存在,则使用,否则就从resCode里查找
        if (StringUtils.isBlank(errorMsg)) {
            errorMsg = ResCodeMessageCache.getMessageDesc(code);
        }
        resultJson.put("resDesc", errorMsg);
        return resultJson;
    }
}
